package com.jyw.network;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;

/**
 * @author simonw
 * @version 1.0
 * @created 2016/2/23
 */
public class OkHttpManager {
    private static final String TAG = "OkHttpManager";
    private static OkHttpManager mInstance;
    private OkHttpClient mOkHttpClient;
    private Gson mGson;

    private OkHttpManager() {
        mOkHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {

                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = new ArrayList<>();
                        cookies.add(new Cookie.Builder().domain("app.jyw0377.com").path("/").
                                name("PHPSESSID").value("01234567890").build());
                        return cookies;
                    }
                })
                .build();
        mGson = new Gson();
    }

    public static OkHttpManager getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpManager.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 用于异步onResponse的Toast
     */
    public static void backgroundThreadShortToast(final Context context,
                                                  final String msg) {
        if (context != null && msg != null) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    public OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }

    public Gson getGSON() {
        return mGson;
    }
}
